import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { AccountEntity } from '@src/entities/model/admin/system/account.entity';
import { CreateAccountDto } from '@src/controllers/admin/system/account/dto/create.account.dto';
import { UpdateAccountDto } from '@src/controllers/admin/system/account/dto/update.account.dto';

@Injectable()
export class AccountService {
  constructor (
    @InjectRepository(AccountEntity)
    private readonly accountRepository: Repository<AccountEntity>,
  ) { }

  async createAccount(createAccountDto: CreateAccountDto): Promise<AccountEntity> {
    const { username, password } = createAccountDto;
    const isExist = await this.accountRepository.findOne({ where: { username, isDel: 0 } });
    if (!isExist) {
      // 使用orm的钩子函数就必须先create,再save
      const user = await this.accountRepository.create(createAccountDto);
      await this.accountRepository.save(user);
      return user;
    } else {
      throw new HttpException(`【${username}】已经存在不能重复添加`, HttpStatus.OK)
    }
  }

  async deleteAccountById(id: number): Promise<string> {
    const { raw: { affectedRows } } = await this.accountRepository.update({ id }, { isDel: 1 });
    if (affectedRows) {
      return '删除成功';
    } else {
      return '删除失败';
    }
  }

  async modifyAccountById(id: number, updateAccountDto: UpdateAccountDto): Promise<string> {
    return '成功';
  }

  async accountList(): Promise<any> {
    const user = await this.accountRepository.find({ where: { isDel: 0 } });
    // return user.toResponseObject(false);
    return user;
  }
}
